package com.acme.service.bank;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

import com.acme.cli.BankApplication;
import com.acme.domain.bank.Bank;
import com.acme.domain.bank.Client;
import com.acme.exceptions.ClientExistsException;
import com.acme.service.bank.impl.BankServiceImpl;

public class BankDataLoader {
	private BankService bankService;
	private BankDataLoaderService loaderService;
	
	public BankDataLoader() { }
	
	/**
	 * Loads a file which contains data feed in the following format: <br>
	 * accounttype=c|s;balance=100;overdraft=50;name=John;gender=m|f;
	 * 
	 * @param bank
	 * @param path
	 * @throws FileNotFoundException
	 */
	public void loadFromFeedFile(final Bank bank, final String path)
			throws FileNotFoundException {

		Scanner in = new Scanner(new File(path));
		String data = "";
		while(in.hasNext()) {
			data+= in.nextLine() + "\n";
		}
		in.close();
		
		this.load(bank, data);
	}
	
	public ArrayList<Client> load(final Bank bank, final String data) {
		loaderService = new BankDataLoaderService();
		ArrayList<Client> clients = null;
		clients = loaderService.generateClients(data);
		
		if(clients != null) {
			for(Client client: clients) {
				try {
					bankService.addClient(bank, client.getName(), client.getGender());
				} catch (ClientExistsException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return clients;
		}
		return null;
	}
	
	public ArrayList<Client> addClientsFromFeed(String newClientsFeedData) {
		Bank bank = null;
		try {
			bank = BankApplication.loadBankFromDataSource();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		bankService = new BankServiceImpl();
		ArrayList<Client> clients = this.load(bank, newClientsFeedData);
		try {
			BankApplication.saveTheBankToDataSource(bank);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return clients;
	}
	
	public BankService getBankService() {
		return bankService;
	}

	public void setBankService(final BankService bankService) {
		this.bankService = bankService;
	}
}